import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import {verifyCode} from "@/api/verifyCode";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const {username, password, code, uuid} = userInfo;
    return new Promise((resolve, reject) => {
      verifyCode({verifyCode: code , uuid: uuid}).then(
        response => {
          if (response.code===0){
            login({ username: username.trim(), password: password }).then(response => {
              const { data } = response

              //存放Token 以后每次请求都携带
              commit('SET_TOKEN', data.Token)
              setToken(data.Token)

              const { userLoginName, userAvatar } = data.userInfo
              /*相当于 userLoginName = data.userInfo.userLoginName*/

              commit('SET_NAME', userLoginName)
              commit('SET_AVATAR', userAvatar )
              localStorage.setItem("name", userLoginName);
              localStorage.setItem("avatar", userAvatar);
              /*vuex并不能解决跨页面数据共享的问题，他解决的主要问题是不同组件间的通信，比如兄弟组件间通信，要是不用vuex会非常麻烦，也不好维护，使用vuex之后，能进行统一管理，非常方便*/

              resolve(data.userInfo)
            }).catch(error => {
              reject(error)
            })

          }
        }
      ).catch(
        error =>{
          debugger
          reject(error)
        }
      )

    })
  },

  // get user info
  // 这里是在每次beforeEach跳转的时候进行个人信息获取
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {

        // 把token给后端 让后端判断用户信息并返回过来
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        // commit('SET_TOKEN', getToken())

        //发出请求 后端登出
        logout()

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

